package com.growthserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.growthserver.entity.RuleTypeEnum;
import com.growthserver.entity.TMemberEntity;
import com.growthserver.entity.TTaskRuleDetailEntity;
import com.growthserver.entity.TTaskRuleDoRecordEntity;
import com.growthserver.mapper.AppletMapper;
import com.growthserver.mapper.IntegralGrowthMapper;
import com.growthserver.param.IntegralParam;
import com.growthserver.service.AppletService;
import com.growthserver.service.TaskRuleVerificationService;
import com.growthserver.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaskRuleVerificationServiceImpl implements TaskRuleVerificationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskRuleVerificationService.class);

    @Autowired
    private AppletService appletService;

    @Autowired
    private AppletMapper appletMapper;

    @Autowired
    private IntegralGrowthMapper integralGrowthMapper;

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    @Value("askTopic")
    private String askTopic;
    @Value("${internalConsumerTopic:TOPIC_INTERNAL_MY_CONSUMER}")
    private String internalConsumerTopic;

    @Value("${integralTimeRange}")
    private String integralTimeRange;


    @Override
    public List<HashMap<String, String>> ruleVerification(IntegralParam integralParam) {
        // 用户id非空判断
        if (integralParam.getUserId() != null && integralParam.getType() != null) {
            //获取用户等级
            TMemberEntity memberEntity = appletService.getUserLevel(integralParam.getUserId());
            //TODO 任务规则根据类型进行规则判定
            //活动抽奖类,特别分类.因为暂时无此类的规则
            if (RuleTypeEnum.HD.getCode().equals(integralParam.getType())) {
                return activeRule(integralParam);
                //普通 签到,注册,点赞,转发...
            } else {
                //通过 用户等级,用户类型 当前时间 参数, 获取对应规则模板  或者 类型通用
                List<TTaskRuleDetailEntity> tIovTaskRuleDetails = integralGrowthMapper.selectByMouldAndUserType(memberEntity.getUserType(),
                        memberEntity.getLevelNum(), integralParam.getType());
                //判断规则是否存在
                if (!tIovTaskRuleDetails.isEmpty()) {
                    Optional<TTaskRuleDetailEntity> max = tIovTaskRuleDetails.stream()
                            .max(Comparator.comparing(TTaskRuleDetailEntity::getEveryDay));
                    int maxEntityValue = Integer.parseInt(max.get().getEveryDay());
                    //TODO 进行规则过滤,今日完成过任务的,将不再继续加积分
                    List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntityList = appletMapper.selectTTaskRuleDoRecordByUserId(integralParam.getUserId(), integralParam.getType());
                    //如果记录为空 或者 今日积分获取未达到目标最大值 则进行积分,成长值获取
                    if(RuleTypeEnum.GRXX.getCode().equals(integralParam.getType())){
                        //查询记录表是否存在数据
                        String taskRuleId = appletMapper.selectTTaskRuleDoRecordByUserIdType(integralParam.getUserId());
                        if(taskRuleId != null){
                            return null;
                        }
                    }
                    if(tTaskRuleDoRecordEntityList.isEmpty() || maxEntityValue > tTaskRuleDoRecordEntityList.size()) {
                        return signInTask(integralParam, tIovTaskRuleDetails);
                    }
                } else {
                    return null;
                }
            }
        }
        //无用户id或者操作类型为空
        return null;
    }

    /**
     * taskRule
     */
    private List<HashMap<String,String>> signInTask(IntegralParam integralParam, List<TTaskRuleDetailEntity> tTaskRuleDetailEntities) {
        List<HashMap<String,String>> arrayList = new ArrayList<>();
        if(!tTaskRuleDetailEntities.isEmpty()) {
            List<String> taskRuleIdList = tTaskRuleDetailEntities.stream()
                    .map(TTaskRuleDetailEntity::getTaskRuleId) // 假设TTaskRuleDetailEntity有一个名为getPropertyName的方法
                    .collect(Collectors.toList());
            String taskRuleIds = String.join(",", taskRuleIdList);
            //进行每日任务 积分获取
            commonCode(integralParam,tTaskRuleDetailEntities,taskRuleIds);
            // 规则校验
            if (RuleTypeEnum.QD.getCode().equals(integralParam.getType())) {
                for (TTaskRuleDetailEntity tTaskRuleDetailEntity : tTaskRuleDetailEntities) {
                    arrayList.add(typeSignIntegralGrant(tTaskRuleDetailEntity, integralParam));
                }
            } else {
                for (TTaskRuleDetailEntity tTaskRuleDetailEntity : tTaskRuleDetailEntities) {
                    arrayList.add(periodicRules(tTaskRuleDetailEntity, integralParam));
                }
            }
        }
        return arrayList;
    }


    /**
     * 分类计算
     */
    private HashMap<String,String> periodicRules(TTaskRuleDetailEntity tTaskRuleDetailEntity, IntegralParam integralParam) {
        // 进行 字段值判断,进行计算规则 天
        switch (tTaskRuleDetailEntity.getTaskFrequency()){
            //频率 天
            case  "1" :
            return typeDayIntegralGrant(tTaskRuleDetailEntity,integralParam);
            //频率 周
            case "2":
                return typeWeekIntegralGrant(tTaskRuleDetailEntity,integralParam);
            //频率 月
            case "3":
                return typeMonthIntegralGrant(tTaskRuleDetailEntity,integralParam);
        }
        return null;
    }

    /**
     * 活动
     */
    private List<HashMap<String,String>> activeRule(IntegralParam integralParam){
        TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = new TTaskRuleDoRecordEntity();
        //类型名称
        tTaskRuleDoRecordEntity.setTaskType(integralParam.getType());
        //活动名称
        tTaskRuleDoRecordEntity.setActionType(integralParam.getActiveName());
        //活动ID
        tTaskRuleDoRecordEntity.setTaskRuleId(integralParam.getActiveId());
        //用户ID
        tTaskRuleDoRecordEntity.setUserId(integralParam.getUserId());
        //积分值
        tTaskRuleDoRecordEntity.setIntegralValue(integralParam.getIntegralValue());
        //成长值
        tTaskRuleDoRecordEntity.setGrowthValue(integralParam.getGrowthValue());
        // 积分类型 1 增加 0扣减
        if(integralParam.getDoType().equals("1")){
            integralGrowthMapper.updateIntegralBudge(integralParam.getBudgetRequestNum(), integralParam.getIntegralValue());
        }else {
            //获取即将过期积分倒序
            List<TTaskRuleDoRecordEntity> list = integralGrowthMapper.selectWillExpIntegralValue(integralParam.getUserId());
            //积分扣减
            deductionIntegralValue(integralParam.getIntegralValue(),list,new ArrayList<>());
        }
        tTaskRuleDoRecordEntity.setIntegralType(integralParam.getDoType());
        LocalDateTime localDateTime = LocalDateTime.now().plusYears(Integer.parseInt(integralTimeRange));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        tTaskRuleDoRecordEntity.setIntegralEndTime(dateTimeFormatter.format(localDateTime));
        //积分日志
        //更新 会员表信息
        kafkaTemplate.send(internalConsumerTopic,new Gson().toJson(tTaskRuleDoRecordEntity));
        return new ArrayList<>();
    }

    //积分扣减
    private void deductionIntegralValue(String integralValue, List<TTaskRuleDoRecordEntity> list, List<String> arrayList) {
        String deductBatchNum = UUID.randomUUID().toString();
        int i = Integer.parseInt(integralValue);
        for (TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity : list
        ) {
            i = i - Integer.parseInt(tTaskRuleDoRecordEntity.getIntegralValue());
            if (i == 0) {
                arrayList.add(tTaskRuleDoRecordEntity.getTaskRuleRecordId());
                // 更新数据库 arrayList  USE_FLAG=1
                String useFlag = "1";
                for (String taskRuleRecordId:arrayList
                ) {
                    integralGrowthMapper.tTaskRuleDoRecordUpdateById(taskRuleRecordId,useFlag,null,deductBatchNum);
                }
                break;
            } else if (i < 0) {
                String taskRuleRecordId = tTaskRuleDoRecordEntity.getTaskRuleRecordId();
                //剩余积分
                int a = Integer.parseInt(tTaskRuleDoRecordEntity.getIntegralValue()) - Integer.parseInt(integralValue);
                //进行积分数据更新  REMAIN_INTEGRAL_VALUE = a point.get("id")  USE_FLAG
                tTaskRuleDoRecordEntity.setUseFlag("2");
                String useFlag = "2";
                integralGrowthMapper.tTaskRuleDoRecordUpdateById(taskRuleRecordId,useFlag,String.valueOf(a),deductBatchNum);
                //更新剩余积分改为USE_FLAG=1
                useFlag ="1";
                for (String taskRuleRecordId1:arrayList
                ) {
                    integralGrowthMapper.tTaskRuleDoRecordUpdateById(taskRuleRecordId1,useFlag,null,deductBatchNum);
                }
                break;
            }else {
                String taskRuleRecordId = tTaskRuleDoRecordEntity.getTaskRuleRecordId();
                arrayList.add(taskRuleRecordId);
            }
        }
    }



    /**
     *  日常任务签到 每天类型  分连续,不连续
     */
    private HashMap<String, String> typeSignIntegralGrant(TTaskRuleDetailEntity tTaskRuleDetailEntity, IntegralParam integralParam) {
        //通过userId 类型 获取任务规则
        String linkUrl = null;
        String activeId = null;
        String activeTypeCode = null;
        List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities = integralGrowthMapper.selectByTypeNumTDayContinuous(integralParam.getUserId(),integralParam.getType());
        if (!tTaskRuleDoRecordEntities.isEmpty()) {
            // //判断类是否未连续
            if (tTaskRuleDetailEntity.getIsContinuous().equals("1")) {
                //是否是连续 ,判断是否达到次数  满足签到要求  地址连接
                //获取日志信息,
                TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = tTaskRuleDoRecordEntities.get(0);
                //判断连续天数合日志记录数是否相等 && 判断日志记录数合规则对应线序天数是否相等
                if (Integer.parseInt(tTaskRuleDoRecordEntity.getDays()) == tTaskRuleDoRecordEntities.size() &&
                        tTaskRuleDetailEntity.getContinuousDays().equals(tTaskRuleDoRecordEntity.getDays())) {
                    //连续判断用户签到次数是否满足邀请
                    linkUrl = tTaskRuleDetailEntity.getLinkUrl();
                    activeId = tTaskRuleDetailEntity.getActiveId();
                    activeTypeCode = tTaskRuleDetailEntity.getActiveTypeCode();
                }
            } else {
                //不连续计算
                if (Integer.parseInt(tTaskRuleDetailEntity.getContinuousDays()) == tTaskRuleDoRecordEntities.size()) {
                    //非连续判断用户签到次数是否满足邀请
                    linkUrl = tTaskRuleDetailEntity.getLinkUrl();
                    activeId = tTaskRuleDetailEntity.getActiveId();
                    activeTypeCode = tTaskRuleDetailEntity.getActiveTypeCode();
                }
            }
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("linkUrl",linkUrl);
        map.put("activeId",activeId);
        map.put("activeTypeCode",activeTypeCode);
        return map;
    }



    /**
     * 日常任务每周类型 不连续
     */
    private HashMap<String, String> typeDayIntegralGrant(TTaskRuleDetailEntity tTaskRuleDetailEntity, IntegralParam integralParam) {
        //通过userId 类型 获取任务规则
        String linkUrl = null;
        String activeId = null;
        String activeTypeCode = null;
        HashMap<String, String> map = new HashMap<>();
        List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities = integralGrowthMapper.selectByTypeNumTNotWeekContinuous(integralParam.getType());
        if (!tTaskRuleDoRecordEntities.isEmpty()) {
            //连续次数,是否达标
            if (Integer.parseInt(tTaskRuleDetailEntity.getActionValue()) == tTaskRuleDoRecordEntities.size()) {
                //非连续判断用户签到次数是否满足邀请
                linkUrl = tTaskRuleDetailEntity.getLinkUrl();
                activeId = tTaskRuleDetailEntity.getActiveId();
                activeTypeCode = tTaskRuleDetailEntity.getActiveTypeCode();
            }
            map.put("linkUrl", linkUrl);
            map.put("activeId", activeId);
            map.put("activeTypeCode", activeTypeCode);
        }
        return map;
    }

    /**
     * 日常任务每周类型 不连续
     */
    private HashMap<String,String> typeWeekIntegralGrant(TTaskRuleDetailEntity tTaskRuleDetailEntity, IntegralParam integralParam) {
        String weekEndTime = null;
        String monthEndTime = null;
        //通过userId 类型 获取任务规则
        String linkUrl = null;
        String activeId = null;
        String activeTypeCode = null;
        List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities = integralGrowthMapper.selectByTypeNumTNotWeekContinuous(integralParam.getType());
        if (!tTaskRuleDoRecordEntities.isEmpty()) {
            //不连续计算
            if (Integer.parseInt(tTaskRuleDetailEntity.getContinuousDays()) == tTaskRuleDoRecordEntities.size()) {
                //非连续判断用户签到次数是否满足邀请
                linkUrl = tTaskRuleDetailEntity.getLinkUrl();
                activeId = tTaskRuleDetailEntity.getActiveId();
                activeTypeCode =tTaskRuleDetailEntity.getActiveTypeCode();
            }
            //拿到 周截止日,月截止日
            weekEndTime = tTaskRuleDoRecordEntities.get(0).getWeekEndTime();
            monthEndTime = tTaskRuleDoRecordEntities.get(0).getMonthEndTime();
            //时间月截止日判断
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean contains = monthEndTime.contains(simpleDateFormat.format(new Date()));
            if(!contains){
                monthEndTime = null;
            }
        }else {
            //获取最后的
            TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = integralGrowthMapper.selectByTypeNumTNotWeekEndContinuous(integralParam.getType());
            monthEndTime = tTaskRuleDoRecordEntity.getMonthEndTime();
            //时间月截止日判断
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean contains = monthEndTime.contains(simpleDateFormat.format(new Date()));
            if(!contains){
                monthEndTime = null;
            }
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("linkUrl",linkUrl);
        map.put("activeId",activeId);
        map.put("activeTypeCode",activeTypeCode);
        return map;
    }

    /**
     * 每月类型 不连续
     */
    private HashMap<String, String> typeMonthIntegralGrant(TTaskRuleDetailEntity tTaskRuleDetailEntity, IntegralParam integralParam) {
        String weekEndTime = null;
        String monthEndTime = null;
        //通过userId 类型 获取任务规则
        String linkUrl = null;
        String activeId = null;
        String activeTypeCode = null;
        List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities = integralGrowthMapper.selectByTypeNumTNotMonthContinuous(integralParam.getType());
        if (!tTaskRuleDoRecordEntities.isEmpty()) {
            //不连续计算
            if (Integer.parseInt(tTaskRuleDetailEntity.getContinuousDays()) == tTaskRuleDoRecordEntities.size()) {
                //非连续判断用户签到次数是否满足邀请
                linkUrl = tTaskRuleDetailEntity.getLinkUrl();
                activeId = tTaskRuleDetailEntity.getActiveId();
                activeTypeCode =tTaskRuleDetailEntity.getActiveTypeCode();
            }
            //拿到 周截止日,月截止日
            weekEndTime = tTaskRuleDoRecordEntities.get(0).getWeekEndTime();
            monthEndTime = tTaskRuleDoRecordEntities.get(0).getMonthEndTime();
            //时间周截止日判断
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean contains = weekEndTime.contains(simpleDateFormat.format(new Date()));
            if(!contains){
                weekEndTime = null;
            }
        }else {
            //获取最后的
            TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = integralGrowthMapper.selectByTypeNumTNotWeekEndContinuous(integralParam.getType());
            weekEndTime = tTaskRuleDoRecordEntity.getWeekEndTime();
            //时间周截止日判断
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean contains = weekEndTime.contains(simpleDateFormat.format(new Date()));
            if(!contains){
                weekEndTime = null;
            }
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("linkUrl",linkUrl);
        map.put("activeId",activeId);
        map.put("activeTypeCode",activeTypeCode);
        return map;
    }

    /**
     * 公共代码
     */
    private void commonCode(IntegralParam integralParam, List<TTaskRuleDetailEntity> tTaskRuleDetailEntities,String taskRuleIds) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        TTaskRuleDetailEntity tTaskRuleDetailEntity = tTaskRuleDetailEntities.get(0);
        //积分值存入日志表进行留痕
        TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = new TTaskRuleDoRecordEntity();
        tTaskRuleDoRecordEntity.setTaskType(tTaskRuleDetailEntity.getActionType());
        tTaskRuleDoRecordEntity.setActionType(tTaskRuleDetailEntity.getActionType());
        tTaskRuleDoRecordEntity.setUserId(integralParam.getUserId());
        tTaskRuleDoRecordEntity.setTaskRuleId(taskRuleIds);
        tTaskRuleDoRecordEntity.setGrowthValue(tTaskRuleDetailEntity.getGrowthValue());
        tTaskRuleDoRecordEntity.setIntegralValue(tTaskRuleDetailEntity.getIntegralValue());
        tTaskRuleDoRecordEntity.setBudgetRequestNum(tTaskRuleDetailEntity.getBudgetRequestNum());
        tTaskRuleDoRecordEntity.setDepartment(tTaskRuleDetailEntity.getDepartment());
        // 获取 任务规则积分期时间
        String expDate = integralGrowthMapper.selectTaskRuleByTaskRuleId(tTaskRuleDetailEntity.getTaskId());
        tTaskRuleDoRecordEntity.setIntegralEndTime(expDate);
        //获取截至周,截至月
        List<TTaskRuleDoRecordEntity> tTaskRuleDoRecordEntities = integralGrowthMapper.selectByTypeNumTDayContinuous(integralParam.getUserId(),integralParam.getType());
        if(!tTaskRuleDoRecordEntities.isEmpty() ){
            TTaskRuleDoRecordEntity tTaskRuleDoRecord = tTaskRuleDoRecordEntities.get(0);
            String weekEndTime = tTaskRuleDoRecord.getWeekEndTime();
            String monthEndTime = tTaskRuleDoRecord.getMonthEndTime();
            try {
                //判断是否比现在日期大,否则 新建
                if (weekEndTime != null && new Date().before(simpleDateFormat.parse(weekEndTime))) {
                    tTaskRuleDoRecordEntity.setWeekEndTime(weekEndTime);
                } else {
                    tTaskRuleDoRecordEntity.setWeekEndTime(DateUtils.getMax(6));
                }
                //判断是否比现在日期大,否则 新建
                if (monthEndTime != null && new Date().before(simpleDateFormat.parse(monthEndTime))) {
                    tTaskRuleDoRecordEntity.setMonthEndTime(monthEndTime);
                } else {
                    tTaskRuleDoRecordEntity.setMonthEndTime(DateUtils.getMax(29));
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }else {
            tTaskRuleDoRecordEntity.setWeekEndTime(DateUtils.getMax(6));
            tTaskRuleDoRecordEntity.setMonthEndTime(DateUtils.getMax(29));
        }
        //邀请 注册,试驾,订车,购车 MQ
        if(RuleTypeEnum.HYZC.getCode().equals(integralParam.getType())
                || RuleTypeEnum.HYSJ.getCode().equals(integralParam.getType())){
            //用户ID,积分值,成长值,记录编号  发送json格式消息
            JSONObject objects = new JSONObject();
            objects.put("userId",integralParam.getUserId());
            objects.put("integralValue",tTaskRuleDoRecordEntity.getIntegralValue());
            objects.put("growthValue",tTaskRuleDoRecordEntity.getGrowthValue());
            objects.put("id",integralParam.getId());
            kafkaTemplate.send(askTopic,objects.toJSONString());
        }
        //发送MQ数据
        kafkaTemplate.send(internalConsumerTopic,new Gson().toJson(tTaskRuleDoRecordEntity));
    }
}
